package com.maopuyu.controllers;

import com.maopuyu.entity.BaseMessage;
import com.maopuyu.entity.DistrictSchool;
import com.maopuyu.entity.HousingEstate;
import com.maopuyu.entity.TextMessage;
import com.maopuyu.services.DistrictSchoolService;
import com.maopuyu.services.HosingEstateService;
import com.maopuyu.utils.RequestUtils;
import com.maopuyu.utils.WXReturnMsgUtils;
import com.maopuyu.utils.XMLBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping(value = "/api/weixin")
public class WeiXinController {
    //    AppId  wx1824e1e334b32839
    //    AppSecret  a7e27bac7192332e9df5af4d8e26506f
    //    Token shanghai2020
    //    EncodingAESKey PasqLgwEIn22pduW1VdrKVFKhaNygkeb8nHBDdHmVES
    private String developer = "shanghairuxue";

    @Autowired
    private HosingEstateService hosingEstateService;

    @Autowired
    private DistrictSchoolService districtSchoolService;

    private String verify(String nonce, String token, String timestamp, String echostr, String signature) {
        ArrayList<String> list = new ArrayList<String>();
        list.add(nonce);
        list.add(timestamp);
        list.add(token);
        Collections.sort(list);
        String temSig = DigestUtils.sha1Hex(list.get(0) + list.get(1) + list.get(2));
        if (temSig.equals(signature))
            return echostr;
        else
            return "";
    }

    private BaseMessage setReturnMsg(String msgType, String fromUser) {
        TextMessage xml = new TextMessage();
        xml.setFromUserName("<![CDATA[" + developer + "]]>");
        xml.setMsgType("<![CDATA[" + msgType + "]]>");
        xml.setToUserName("<![CDATA[" + fromUser + "]]>");
        xml.setMsgType("<![CDATA[" + msgType + "]]>");
        xml.setCreateTime(new Date().getTime());
        return xml;
    }

    private String formSchool(List<HousingEstate> housingEstates) {
        String restr = "";
        for (HousingEstate housingEstate : housingEstates) {
            if (housingEstate.getRemark() == null) {
                housingEstate.setRemark("无");
            }
            if (housingEstate.getCorrespondingSchoolAddress() == null) {
                housingEstate.setCorrespondingSchoolAddress("略");
            }

            restr = "对口学校：'" + housingEstate.getCorrespondingSchool() + '\'' +
                    "\n 学校地址：'" + housingEstate.getCorrespondingSchoolAddress() + '\'' +
                    "\n 学校等级：'" + housingEstate.getCorrespondingSchoolLevel() + '\'' +
                    "\n 学校所属区（县）：'" + housingEstate.getDistrict() + '\'' +
                    "\n 对口小区：'" + housingEstate.getHosingEstateName() + '\'' +
                    "\n 备注：'" + housingEstate.getRemark() + '\'' +
                    ", 年份：" + housingEstate.getYear() + "\n ======================== \n" + restr;
        }
        return restr + "\n 关注上海入学升学公众号，获取更多咨询！！！";
    }

    private String house2School(Map<String, String> map, String fromUser) {
        String msgContent = map.get("Content");
        if (msgContent.contains("住址")) {
            TextMessage xml = (TextMessage) setReturnMsg("text", fromUser);
            String hosingEstateName = msgContent.replace("住址", "").
                    replace("弄", "").replace("号", "").trim();

            List<HousingEstate> housingEstates = hosingEstateService.findHousingEstateByEstateName("%" + hosingEstateName + "%");
            if (housingEstates.isEmpty()) {
                xml.setContent("<![CDATA[如果您住在浦东区，建议您直接回复“住址”+小区的名称或地址\n" +
                        "如果住在其他区，请尝试回复“查对口 xxx区，如  查对口 普陀区”]]>");
            } else {
                xml.setContent("<![CDATA[" + formSchool(housingEstates) + "]]>");
            }
            return XMLBuilder.beanToXml(xml);
        } else if (msgContent.contains("对口")) {
            String district = msgContent.replace("查", "").replace("对口", "");
            DistrictSchool districtSchool = districtSchoolService.findSchoolByDistrict(district);
            return WXReturnMsgUtils.articleMsg(districtSchool, fromUser, developer);
        } else if (msgContent.contains("资料")) {
            String district = msgContent.replace("资料", "").trim();
            DistrictSchool districtSchool = districtSchoolService.findSchoolByDistrict(district);
            TextMessage xml = new TextMessage();
            xml.setFromUserName("<![CDATA[" + developer + "]]>");
            xml.setMsgType("<![CDATA[text]]>");
            xml.setToUserName("<![CDATA[" + fromUser + "]]>");
            xml.setCreateTime(new Date().getTime());
            xml.setContent("<![CDATA[" + districtSchool.getTitle() + "\n" + districtSchool.getUrl() + "]]>");
            return XMLBuilder.beanToXml(xml);
        } else {
            return "";
        }

    }

    //receive msg
    @RequestMapping(value = "/verify",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_XML_VALUE)
    public String handleMsg(@RequestBody Map<String, String> map) {
        String fromUser = map.get("FromUserName");
        if ("text".equals(map.get("MsgType"))) {
            return house2School(map, fromUser);
        } else {
            return "";
        }
    }

    @RequestMapping(value = "/verify", method = RequestMethod.GET)
    public String sxrx(@RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("echostr") String echostr) {
        String token = "shanghai2020";
        return verify(nonce, token, timestamp, echostr, signature);
    }

    /*
    Get Access Token
    * */
    @RequestMapping(value = "accessToken", method = RequestMethod.GET)
    public String acToken() {
        return RequestUtils.sendWXRequest("https://api.weixin.qq.com/cgi-bin/" +
                "token?grant_type=client_credential&appid=wx1824e1e334b32839&secret=a7e27bac7192332e9df5af4d8e26506f");
    }


    @RequestMapping(value = "/modu", method = RequestMethod.GET)
    public String modu_verify(@RequestParam("signature") String signature,
                              @RequestParam("timestamp") String timestamp,
                              @RequestParam("nonce") String nonce,
                              @RequestParam("echostr") String echostr) {
        // EncodingAESKey 4ESb844dXklyeLoxrYYpqtOjFRBO9sYs8Lf1a2AHFaC
        // AppSecret 53951b64932a87be4843d68284cd1852
        // AppId wxd056e26a45d305c9
        String token = "68cb6fa0d7c4f97512dd5ba4e1d130ed";
        return verify(nonce, token, timestamp, echostr, signature);
    }


    @RequestMapping(value = "/modu", method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE)
    public String modu_handle_msg(@RequestBody Map<String, String> map) {
        String modu = "wzmodu";
        String fromUser = map.get("FromUserName");
        return "";
    }
}
